# coding=utf-8
"""
author:董新强
createdate: 2024/2/28 13:41
description: 
"""
from datetime import datetime
from os import walk
from os.path import join
from threading import Thread
from time import sleep

import requests
import wx
import wx.xrc


class HttpDoc(wx.Frame):

    def __init__(self, parent):
        self.continue_flag = True;

        self._api_dic = {}
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition, size=wx.Size(1415, 1290), style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)

        self.logdir = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, (0, 0), (900, 30), style=wx.TE_MULTILINE)
        self.txtOut = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, (0, 30), (900, 1175), style=wx.TE_MULTILINE)
        self.txtScript = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, (900, 0), (500, 800), style=wx.TE_MULTILINE)

        self.btnGet = wx.Button(self, wx.ID_ANY, u"running..", (0, 1205), (75, 55), 0)
        self.btnGet.Bind(wx.EVT_BUTTON, self.continue_or_stop)

        self.lbTs = wx.StaticText(self, wx.ID_ANY, u"", (100, 1220), (75, 25), 0)

        self.logdir.SetValue(r'C:\projects\hminew\RobProxy\bin\Debug\smlog')

        self.txtScript.SetValue(self.initScript())

        self.btnExecute = wx.Button(self, wx.ID_ANY, u"执行脚本", (910, 810), (100, 55), 0)
        self.btnSwitchHand = wx.Button(self, wx.ID_ANY, u"SwitchHand", (1020, 810), (100, 55), 0)
        self.btnSwitchAuto = wx.Button(self, wx.ID_ANY, u"SwitchAuto", (1130, 810), (100, 55), 0)

        self.btnResume = wx.Button(self, wx.ID_ANY, u"继续", (910, 870), (100, 55), 0)
        self.btnStop = wx.Button(self, wx.ID_ANY, u"停止", (1020, 870), (100, 55), 0)
        self.btnExit = wx.Button(self, wx.ID_ANY, u"退出", (1130, 870), (100, 55), 0)

        self.btnNextStep = wx.Button(self, wx.ID_ANY, u"下一步", (910, 930), (100, 55), 0)
        self.btnNextBreadPoints = wx.Button(self, wx.ID_ANY, u"下一断点", (1020, 930), (100, 55), 0)
        self.btnEnableDebug = wx.Button(self, wx.ID_ANY, u"进入调试", (1130, 930), (100, 55), 0)
        self.btnDisableDebug = wx.Button(self, wx.ID_ANY, u"退出调试", (1240, 930), (100, 55), 0)

        self.btnSpeedlPlus = wx.Button(self, wx.ID_ANY, u"speedl+", (910, 990), (100, 55), 0)
        self.btnSpeedlMinus = wx.Button(self, wx.ID_ANY, u"speedl-", (1020, 990), (100, 55), 0)
        self.btnSpeedjPlus = wx.Button(self, wx.ID_ANY, u"speedj+", (1130, 990), (100, 55), 0)
        self.btnSpeedjMinus = wx.Button(self, wx.ID_ANY, u"speedj-", (1240, 990), (100, 55), 0)

        self.btnSpeedPlus = wx.Button(self, wx.ID_ANY, u"speed+", (910, 1050), (100, 55), 0)
        self.btnSpeedMinus = wx.Button(self, wx.ID_ANY, u"speed-", (1020, 1050), (100, 55), 0)
        self.btnSpeedStop = wx.Button(self, wx.ID_ANY, u"speedStop", (1130, 1050), (100, 55), 0)

        self.btnExecute.Bind(wx.EVT_BUTTON, self.execute_cmd)
        self.btnSwitchHand.Bind(wx.EVT_BUTTON, self.switchHand)
        self.btnSwitchAuto.Bind(wx.EVT_BUTTON, self.switchAuto)

        self.btnNextStep.Bind(wx.EVT_BUTTON, self.debugNextStep)
        self.btnNextBreadPoints.Bind(wx.EVT_BUTTON, self.debugNextBreakPoint)
        self.btnEnableDebug.Bind(wx.EVT_BUTTON, self.debugEnable)
        self.btnDisableDebug.Bind(wx.EVT_BUTTON, self.debugDisable)

        self.btnResume.Bind(wx.EVT_BUTTON, self.resume)
        self.btnStop.Bind(wx.EVT_BUTTON, self.stop)
        self.btnExit.Bind(wx.EVT_BUTTON, self.exitScript)

        # --------------------------手动---------------------------
        self.btnSpeedlPlus.Bind(wx.EVT_BUTTON, self.speedlPlus)
        self.btnSpeedlMinus.Bind(wx.EVT_BUTTON, self.speedlMinus)
        self.btnSpeedjPlus.Bind(wx.EVT_BUTTON, self.speedJPlus)
        self.btnSpeedjMinus.Bind(wx.EVT_BUTTON, self.speedJMinus)

        self.btnSpeedPlus.Bind(wx.EVT_BUTTON, self.speedPLus)
        self.btnSpeedMinus.Bind(wx.EVT_BUTTON, self.speedMinus)
        self.btnSpeedStop.Bind(wx.EVT_BUTTON, self.speed_stop)

        self._speed = 20

        self.url = 'http://127.0.0.1:8888/'

        Thread(target=self.get_logs).start()

    def speed_j(self, flag=1):
        js = [0.1 * flag for v in range(6)]
        try:
            requests.post(self.url, data=self.gen_json(f"speed:J:{js[0]},{js[1]},{js[2]},{js[3]},{js[4]},{js[5]}"))
        except:
            pass

    def speed_l(self, flag):
        ps = [0.05 * flag for v in range(6)]
        try:
            requests.post(self.url, data=self.gen_json(f"speed:L:{ps[0]},{ps[1]},{ps[2]},{ps[3]},{ps[4]},{ps[5]}"))
        except:
            pass

    def speed_stop(self, e):
        try:
            requests.post(self.url, data=self.gen_json("speed:S:0,0,0,0,0,0"))
        except:
            pass

    def speed(self):
        try:
            requests.post(self.url, data=self.gen_json(f"speed:V:{self._speed},0,0,0,0,0"))
        except:
            pass

    def speedPLus(self, e):
        if self._speed < 90:
            self._speed += 10
        self.speed()

    def speedMinus(self, e):
        if self._speed > 10:
            self._speed -= 10
        self.speed()

    def speedlPlus(self, e):
        self.speed_l(1)

    def speedlMinus(self, e):
        self.speed_l(-1)

    def speedJPlus(self, e):
        self.speed_j(1)

    def speedJMinus(self, e):
        self.speed_j(-1)

    def gen_json(self, content):
        content = f"{{\"data\":\"{str(content)}\"}}"
        print(content)
        return content

    def continue_or_stop(self, event):
        self.continue_flag = not self.continue_flag
        if (self.continue_flag):
            self.btnGet.SetLabel("running..")
        else:
            self.btnGet.SetLabel("stoped")

    def execute_cmd(self, event):
        try:
            requests.post(self.url, data=self.gen_json(self.txtScript.GetValue()))
        except:
            pass

    def switchHand(self, event):
        try:
            requests.post(self.url, data=self.gen_json("SwitchHand"))
        except:
            pass

    def switchAuto(self, event):
        try:
            requests.post(self.url, data=self.gen_json("SwitchAuto"))
        except:
            pass

    def debugEnable(self, event):
        try:
            requests.post(self.url, data=self.gen_json("SmDebugEnable"))
        except:
            pass

    def debugDisable(self, event):
        try:
            requests.post(self.url, data=self.gen_json("SmDebugDisable"))
        except:
            pass

    def debugNextStep(self, event):
        try:
            requests.post(self.url, data=self.gen_json("SmDebugNextStep"))
        except:
            pass

    def debugNextBreakPoint(self, event):
        try:
            requests.post(self.url, data=self.gen_json("SmNextBreakPoints"))
        except:
            pass

    def resume(self, event):
        try:
            requests.post(self.url, data=self.gen_json("SmResume"))
        except:
            pass

    def stop(self, event):
        try:
            requests.post(self.url, data=self.gen_json("SmStop"))
        except:
            pass

    def exitScript(self, event):
        try:
            requests.post(self.url, data=self.gen_json("SmTerminate"))
        except:
            pass

    def get_logs(self):
        length = 0
        while True:
            sleep(1)
            if not self.continue_flag:
                continue
            length = self._get_logs(length)

    def _get_logs(self, length):
        try:
            d = self.logdir.GetValue()
            for root, _, files in walk(d):
                if not files: return 0
                files.sort(reverse=True)
                fname = join(root, files[0])
                content = open(fname, 'r').readlines()

                l = len(content)

                self.lbTs.SetLabel(str(datetime.now()))

                if length == l:
                    return l
                content.reverse()

                self.txtOut.SetValue(''.join(content))

                return l

        except Exception as e:
            self.txtOut.SetValue(str(e))
            return 0

    def initScript(self):
        content = """-- lua script
use_tool("default")
use_wobj("default")
set_joints_speed(45,20) -- 设置关节速率为45%
set_tail_speed(50,20) -- 设置速度为50mm/s
wait(1)

movej({15,-50,117,-82,-85,0}) -- debug
curpos = get_tcp()
curpos[1]=curpos[1]+10
-- movep(curpos) -- debug 

curpos = get_tcp()
curpos[6]=curpos[1]+10
-- movel(curpos) -- debug

n=0
while (n<3) do
	movej_d({1,1,10,0,0,0}) -- debug
	n=n+1
end

c= get_tcp()
t= {192.349,293.436,566.417,-107.94,1.54,-67.24}
movep(t)

delta={}
for i=1,6 do
	delta[i]=c[i]-t[i]
end

wait(10)
movep_d(delta)
movel(t)

curjs = get_joints()
print(curjs)
tool(2,1) -- 工具执行动作
exit()
------ 函数结束-----------------
"""
        return content


if __name__ == '__main__':
    app = wx.App()
    win = HttpDoc(parent=None)
    win.Show()
    app.MainLoop()
